<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import router from '@/router'
import { useLoginStore } from '@/store/useLoginStore'

// 表单数据
const username = ref('')
const password = ref('')

// 使用 store
const loginStore = useLoginStore()

// 登录方法
const login = () => {
  const loginData = {
    username: username.value,
    password: password.value
  }

  console.log('提交登录数据:', loginData)

  axios.post('http://localhost:8080/user/login', loginData).then(res => {
    if (res.data.code === 200) {
      // 假设后端返回的是一个 Merchant 数组
      const merchantList = res.data.data

      console.log('登录成功，返回的商家数据:', merchantList)

      loginStore.isLogin = true
      loginStore.merchants = merchantList // 存入数组

      // 跳转到主页
      router.push('/')
    } else {
      alert("登录失败：" + res.data.message || "用户名或密码错误")
    }
  }).catch(err => {
    console.error('登录请求出错:', err)
    alert("网络错误，请重试")
  })
}

// 注册/申请商铺页面跳转
const register = () => {
  router.push('/register')
}
</script>

<template>
  <div class="container">
    <h1>登录</h1>
    <input v-model="username" placeholder="用户名" />
    <input v-model="password" type="password" placeholder="密码" />
    <button @click="login">登录</button>
    <button @click="register">注册</button>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
}
</style>